package hy.day3_01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cookie/*")
public class HelloServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        System.out.println("servletPath:"+req.getServletPath()+",uri:"+req.getRequestURI());
        String urlPath = req.getRequestURI(); //包含项目名路径
        if(urlPath.contains("add")){
            add(req,resp);
        }else if(urlPath.contains("select")){
            select(req,resp);
        }else if(urlPath.contains("delete")){
            delete(req,resp);
        }else if(urlPath.contains("modify")){
            modify(resp);
        }
    }
    void add(HttpServletRequest req,HttpServletResponse resp){
        Cookie c = new Cookie("a1","123");
        resp.addCookie(c);
        //url为/day1/demo1/add,默认的cookie路径为/day1/cookie,所以该cookie就保存在浏览器中的路径为/day1/demo1
        c = new Cookie("a2","456");
        c.setPath("/day3_01");
        resp.addCookie(c);
    }
    void select(HttpServletRequest req,HttpServletResponse resp){
    //在浏览器向服务器发送请求时，会根据所请求的url:"/day1/cookie/select",把demo1和其父系路径（父亲，爷爷..，但不包括叔叔，叔爷）中的cookie发送到服务器
        System.out.println("服务器端从客户端收到的cookie信息如下：");
        Cookie[]arr = req.getCookies();
        for (Cookie c : arr) {
            System.out.println(c.getName()+":"+c.getValue());
        }
    }

    /*1.没有专门删除cookie的直接方法，因为cookie存储在客户端
     *2.cookie默认在关闭浏览器时就销毁，如果指定时间，则以指定时间为准，负数无效，0表示立刻销毁
     */
    void delete(HttpServletRequest req,HttpServletResponse resp){
        //删除名字叫a1的cookie,value可随意写一字符串，没用
        Cookie c = new Cookie("a1","4443");
        //要成功删除该cookie就必须修改成跟前面生成时一样路径，否则不成功
        //把存活时间设置成0秒再添加，就变相删除了a1的cookie
        c.setMaxAge(1);
        resp.addCookie(c);
    }
    void modify(HttpServletResponse resp){
        //注意：不能写中文
        Cookie c = new Cookie("a1","hello");
        resp.addCookie(c);
    }
}